const puppeteer = require('puppeteer')

const url = 'https://movie.douban.com/subject/'

const sleep = time => new Promise(resolve => {
    setTimeout(resolve, time)
})

;
(async () => {
    let browser, page, result, video, doubanId = '26741061';
    browser = await puppeteer.launch({
        args: ['--no-sandbox'],
        dumpio: false
    })
    page = await browser.newPage()

    await page.goto(url + doubanId, {
        waitUntil: 'networkidle2'
    })

    await sleep(2000)

    result = await page.evaluate(() => {
        var $ = window.$;
        var it = $('.related-pic-video')
        if (it && it.length > 0) {
            var link = it.attr('href')
            var cover = it.attr('style')
            cover = cover.match(new RegExp('[a-zA-z]+://[^\s]*'))[0]
            return {
                link,
                cover
            }
        }
        return {}
    })

    if (result.link) {
        await page.goto(result.link, {
            waitUntil: 'networkidle2'
        })
        await sleep(1000)
        video = await page.evaluate(() => {
            var $ = window.$;
            var source = $('source')
            if (source && source.length > 0) {
                return source.attr('src')
            }
            return ''
        })
    }
    browser.close()
    process.send({
        doubanId,
        video,
        cover: result.cover
    })
    process.exit(0)
})()